package com.jlkf.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jlkf.dao.TblOrderMapper;
import com.jlkf.dao.TblPushMessageMapper;
import com.jlkf.dao.TblUserMapper;
import com.jlkf.dao.TblUserPurseInfoMapper;
import com.jlkf.pojo.TblFeedback;
import com.jlkf.pojo.TblOrder;
import com.jlkf.pojo.TblPushMessage;
import com.jlkf.pojo.TblSysUser;
import com.jlkf.pojo.TblUser;
import com.jlkf.pojo.TblUserPurseInfo;
import com.jlkf.pojo.TblUserWithdraw;
import com.jlkf.service.ContentService;
import com.jlkf.view.ExcelWithdraw;
import com.platform.server.response.response.pojo.ReturnData;
import com.platform.server.util.DateUtil;
import com.platform.server.util.ExportExcel;
import com.platform.server.util.JiGuangPushUtils;
import com.platform.server.util.StringTools;

@Controller
@RequestMapping("content")
public class ContentController {
	@Autowired
    private ContentService contentService;
	@Autowired
	private TblUserMapper tblUserMapper;
	@Autowired
	private TblUserPurseInfoMapper tblUserPurseInfoMapper;
	@Autowired
	private TblPushMessageMapper tblPushMessageMapper;
	@Autowired
	private TblOrderMapper tblOrderMapper;
	
	@RequestMapping("selectList")
	@ResponseBody
	public ReturnData selectList(String startTime,String endTime,Integer status,Integer pageNumber,Integer pageSize){
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("status", status);
		if(!StringTools.isEmpty(startTime)){
			map.put("startTime", startTime);
		}
		if(!StringTools.isEmpty(endTime)){
			map.put("endTime", endTime);
		}
		PageHelper.startPage(pageNumber,pageSize);
		List<TblUserWithdraw> list = contentService.selectList(map);
		PageInfo<TblUserWithdraw> pageInfo = new PageInfo<>(list);
		return new ReturnData(list,pageInfo.getPages(),(int)pageInfo.getTotal(),200,"提现审核列表");
	}
	
	/**
	 * 提现审核
	 */
	@RequestMapping("updateStatus")
	@ResponseBody
	public ReturnData updateStatus(Long gId, Integer status) {
		TblUserWithdraw withdraw = contentService.getDetail(gId);
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("gId", gId);
		map.put("status", status);
		if(status==2 || status==3){
			map.put("checkTime", new Date());
		}else if (status==5){
			map.put("accountTime", new Date());
		}
		
		int num = contentService.updateStatus(map);
		if(num>0){
			if(status==3 || status==4){
				TblUser user = tblUserMapper.selectByPrimaryKey(Long.valueOf(withdraw.getgUserid()));
				Double money = user.getgUserMoney()+withdraw.getgMoney();
				Map<String, Object> map1 = new HashMap<String,Object>();
				map1.put("gId", Long.valueOf(withdraw.getgUserid()));
				map1.put("money", money);
				int rel = tblUserMapper.updateBalance(map1);
				if(rel>0){
					TblUserPurseInfo info = new TblUserPurseInfo();
					info.setgUserid(Long.valueOf(withdraw.getgUserid()));
					info.setgContent("提现退回");
					info.setgCreatetime(new Date());
					info.setgBalance(money);
					info.setgMoney(withdraw.getgMoney());
					info.setgType(1);
					info.setgStatus(1);
					info.setgTitle("提现审核");
					info.setwId(gId);
					tblUserPurseInfoMapper.insertSelective(info);
				}
			}
			return new ReturnData(200,"操作成功");
		}else{
			return new ReturnData(500,"操作失败");
		}
	}
	
	// 导出报表
	@RequestMapping("exportExcel")
	public void exportExcelInInvoice(HttpServletResponse response,String startTime,String endTime,Integer status){
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("status", status);
		if(!StringTools.isEmpty(startTime)){
			map.put("startTime", startTime);
		}
		if(!StringTools.isEmpty(endTime)){
			map.put("endTime", endTime);
		}
		List<TblUserWithdraw> list = contentService.selectList(map);
		List<Object> list2 = new ArrayList<Object>();
		for(TblUserWithdraw withdraw :list){
			ExcelWithdraw excel = new ExcelWithdraw();
			excel.setAccountName(withdraw.getgAccountName());
			excel.setAccountOptime(DateUtil.format3(withdraw.getgAccountTime()));
			excel.setBackName(withdraw.getgBankName());
			excel.setBankNo(withdraw.getgAccountBank());
			excel.setCheckOptime(DateUtil.format3(withdraw.getgCheckTime()));
			excel.setOptime(DateUtil.format3(withdraw.getgCreateTime()));
			excel.setPhone(withdraw.getPhone());
			excel.setuName(withdraw.getuName());
			excel.setWithdrawMoney(withdraw.getgMoney());
			list2.add(excel);
		}
		String[] titles = { "姓名", "手机号", "账户名称", "提现金额($)", "提现银行", "提现账号","提交时间", "审核时间", "到账时间"};
		ExportExcel.exportExcel("提现审核表.xls", titles, list2, response);
	}
	
	/**
	 * 查看详情
	 */
	@RequestMapping("getWithdrawDetail")
	@ResponseBody
	public ModelAndView getUserDetail(Long gId){
		TblUserWithdraw withdraw = contentService.getDetail(gId);
		ModelAndView andView = new ModelAndView();
    	andView.addObject("withdraw",withdraw);
    	andView.setViewName("jsp/contentManager/details");
		return andView;
	}
	
	/**
	 * 意见反馈列表
	 * @param startTime
	 * @param endTime
	 * @param uName
	 * @param phone
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("getList")
	@ResponseBody
	public ReturnData getList(String startTime,String endTime,String uName,String phone,Integer pageNumber,Integer pageSize){
		Map<String, Object> map = new HashMap<String,Object>();
		if(!StringTools.isEmpty(startTime)){
			map.put("startTime", startTime);
		}
		if(!StringTools.isEmpty(endTime)){
			map.put("endTime", endTime);
		}
		if(!StringTools.isEmpty(uName)){
			map.put("uName", uName);
		}
		if(!StringTools.isEmpty(phone)){
			map.put("phone", phone);
		}
		PageHelper.startPage(pageNumber,pageSize);
		List<TblFeedback> list = contentService.geFeedbackList(map);
		PageInfo<TblFeedback> pageInfo = new PageInfo<TblFeedback>(list);
		return new ReturnData(list,pageInfo.getPages(),(int)pageInfo.getTotal(),200,"意见反馈列表");
	}
	
	/**
	 * 批量删除
	 * @param gId
	 * @return
	 */
	@RequestMapping("delete")
	@ResponseBody
	public ReturnData delete(String gId){
		List<String> list = Arrays.asList(gId.split(","));
		int rel = contentService.deleteList(list);
		if(rel>0){
			return new ReturnData(200,"删除成功");
		}else{
			return new ReturnData(500,"删除失败");
		}
	}
	
	/**
	 * 查看详情
	 */
	@RequestMapping("getFeedbackDetail")
	@ResponseBody
	public ModelAndView getFeedbackDetail(Long gId){
		TblFeedback feedback = contentService.getFeedbackDetail(gId);
		ModelAndView andView = new ModelAndView();
    	andView.addObject("feedback",feedback);
    	andView.setViewName("jsp/contentManager/feedbackDetail");
		return andView;
	}
	
	/**
	 * 推送消息列表
	 * @param startTime
	 * @param endTime
	 * @param status
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("selectMessageList")
	@ResponseBody
	public ReturnData selectMessageList(String startTime,String endTime,Integer status,String title,Integer pageNumber,Integer pageSize){
		Map<String, Object> map = new HashMap<String,Object>();
		if(!StringTools.isEmpty(startTime)){
			map.put("startTime", startTime);
		}
		if(!StringTools.isEmpty(endTime)){
			map.put("endTime", endTime);
		}
		if(status!=null){
			map.put("status", status);
		}
		if(!StringTools.isEmpty(title)){
			map.put("title", title);
		}
		PageHelper.startPage(pageNumber,pageSize);
		List<TblPushMessage> list = contentService.selectPushList(map);
		PageInfo<TblPushMessage> pageInfo = new PageInfo<TblPushMessage>(list);
		return new ReturnData(list,pageInfo.getPages(),(int)pageInfo.getTotal(),200,"推送列表");
	}
	
	
	/**
	 * 新增推送消息
	 */
	@RequestMapping("insertMessage")
	@ResponseBody
	public ReturnData insertMessage(@RequestBody String json,HttpSession session){
		try{
			DateFormat df = new SimpleDateFormat("HH:mm:ss");//创建日期转换对象HH:mm:ss为时分秒，年月日为yyyy-MM-dd  
			TblSysUser user = (TblSysUser) session.getAttribute("sysUser");
			TblPushMessage message = StringTools.json2Obj(json, TblPushMessage.class);
			int num = 0;
			if(message.getgId()==null){
				message.setgUserId(user.getgId());
				message.setgStatus(1);
				num = contentService.insertMessage(message);
			}else{
				message.setgUserId(user.getgId());
				message.setgStatus(1);
				num = contentService.updateMessage(message);
			}
			if(num>0){
				//定时任务为12点推送，如推送时间为今日并且超过12点，即现在推送
		        try {  
		            Date dt1 = df.parse("12:00:00");//将字符串转换为date类型  
		            Date dt2 = df.parse(df.format(new Date()));  
		            if(dt2.getTime()>dt1.getTime()){  
		                pushMessage();
		            }  
		        } catch (ParseException e) {  
		            // TODO Auto-generated catch block  
		            e.printStackTrace();  
		        }  
				return new ReturnData(200,"保存成功");
			}else{
				return new ReturnData(500,"保存失败");
			}
		}catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500,"系统错误");
		}
	}
	
	/**
	 * 查看详情
	 */
	@RequestMapping("getMessageDetail")
	@ResponseBody
	public ModelAndView getMessageDetail(Integer gId,Integer type){
		TblPushMessage message = contentService.selectMessageDetail(gId);
		ModelAndView andView = new ModelAndView();
    	andView.addObject("message",message);
    	if(type==1){ //修改
    		andView.setViewName("jsp/contentManager/updateMessage");
    	}else{ //查询
    		andView.setViewName("jsp/contentManager/messageDetail");
    	}
		return andView;
	}
	
	
	/**
	 * 批量删除
	 * @param gId
	 * @return
	 */
	@RequestMapping("deleteMessage")
	@ResponseBody
	public ReturnData deleteMessage(String gId){
		List<String> list = Arrays.asList(gId.split(","));
		int rel = contentService.deleteMessage(list);
		if(rel>0){
			return new ReturnData(200,"删除成功");
		}else{
			return new ReturnData(500,"删除失败");
		}
	}

	//推送
	private void pushMessage(){
		Map<String, Object> map = new HashMap<String,Object>();
		List<TblPushMessage> list = tblPushMessageMapper.selectByOptime();
		List<TblUser> userInfo = tblUserMapper.getVipUserInfo(map); //vip会员
		List<TblUser> users = tblUserMapper.getIsNotVip(); //非vip用户
		for(TblPushMessage message:list){
			if(message.getgRang()==1){ //全部用户
				JiGuangPushUtils.pushAll(message.getgTitle());
				message.setgStatus(2);
			}else if(message.getgRang()==2){ //vip用户
				for(TblUser user:userInfo){
					TblOrder order = tblOrderMapper.getVipInfo(user.getgId());
					Date validity = new Date();
					if(order!=null){
						//判断vip是否过期
						if(validity.getTime()<=order.getgValidityTime().getTime()){ //未过期
							JiGuangPushUtils.pushTargetForPeople(user.getgId().toString(), message.getgTitle());
							message.setgStatus(2);
						}
					}
				}
			}else if(message.getgRang()==3){ //非vip用户
				for(TblUser user:users){ //未购买vip
					JiGuangPushUtils.pushTargetForPeople(user.getgId().toString(), message.getgTitle());
					message.setgStatus(2);
				}
				for(TblUser user:userInfo){ //购买了vip，判断是否过期
					TblOrder order = tblOrderMapper.getVipInfo(user.getgId());
					Date validity = new Date();
					if(order!=null){
						if(validity.getTime()>order.getgValidityTime().getTime()){
							JiGuangPushUtils.pushTargetForPeople(user.getgId().toString(), message.getgTitle());
							message.setgStatus(2);
						}
					}
				}
			}else if(message.getgRang()==4){ //年度会员
				for(TblUser user:userInfo){
					if(user.getgUserIsVip()==3){
						TblOrder order = tblOrderMapper.getVipInfo(user.getgId());
						Date validity = new Date();
						if(order!=null){
							//判断vip是否过期
							if(validity.getTime()<=order.getgValidityTime().getTime()){ //未过期
								JiGuangPushUtils.pushTargetForPeople(user.getgId().toString(), message.getgTitle());
								message.setgStatus(2);
							}
						}
					}
				}
			}else if(message.getgRang()==5){ //季度会员
				for(TblUser user:userInfo){
					if(user.getgUserIsVip()==2){
						TblOrder order = tblOrderMapper.getVipInfo(user.getgId());
						Date validity = new Date();
						if(order!=null){
							//判断vip是否过期
							if(validity.getTime()<=order.getgValidityTime().getTime()){ //未过期
								JiGuangPushUtils.pushTargetForPeople(user.getgId().toString(), message.getgTitle());
								message.setgStatus(2);
							}
						}
					}
				}
			}else if(message.getgRang()==6){  //月度会员
				for(TblUser user:userInfo){
					if(user.getgUserIsVip()==1){
						TblOrder order = tblOrderMapper.getVipInfo(user.getgId());
						Date validity = new Date();
						if(order!=null){
							//判断vip是否过期
							if(validity.getTime()<=order.getgValidityTime().getTime()){ //未过期
								JiGuangPushUtils.pushTargetForPeople(user.getgId().toString(), message.getgTitle());
								message.setgStatus(2);
							}
						}
					}
				}
			}
			tblPushMessageMapper.updateByPrimaryKeySelective(message);
		}
	}
}
